<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\Session;
class SessionCheck extends Controller
{
    public function __construct()
    { 
        $session = request()->session('uid');
        if(empty($session)){
            $this->redirect('./login');
            die;
        }
        $auth = session('auth');
        $type = session('type');
       /* if($type!='all'){
            if(input('pid')){
                if(!in_array(input('pid'),explode(',',session('pid')))){
                    exit;
                }
            }
            if(input('aid')){
                if(!in_array(input('aid'),explode(',',session('aid')))){
                    exit;
                }
            }
            if(input('aid')){
                if(!in_array(input('aid'),explode(',',session('aid')))){
                    exit;
                }
            }
        }*/
        $action = request()->action();
        $controller = request()->controller();
        if($action != "ajax_get" && $controller !="Material" && $action !='ajax_set'){
            $auth = explode(',',str_replace("|",",",$auth));
            // dump($auth);
            $check = in_array(strtolower($controller.'/'.$action),$auth);
            if(!$check){
                die($controller.'/'.$action.'error');
            }
        }
        $menu_list = [];
        $menu = Db::table("menu")->where('gid',0)->whereIn('auth',session('auth'))->select();
        if(!empty($menu)){
            foreach($menu as $children){
                $children['child'] = Db::table("menu")->where('gid',$children['id'])->whereIn('auth',session('auth'))->select();
                array_push($menu_list,$children);
            }
        }
        $this->menu_list = $menu_list;
        //dump($children);
        // halt($menu_list[0]['child']);
        function pages($table,$where,$page = 1){
            $page = $page?$page:1;
            $list_rows = config('paginate.list_rows');
            $limit = ($page-1) * $list_rows;
            $total = Db::table($table)->whereIn('aid',session('aid'))->where($where)->count();
            $pagetotal = ceil($total/$list_rows);
            return array('limit'=>$limit.",".$list_rows,'pages'=>['page'=>$page,'pagetotal'=>$pagetotal,'total'=>$total]);
        }

        function success($msg = '',$redirecturl = ''){
            return view('public/success',['msg'=>$msg,'url'=>$redirecturl]);
        }

        function error($msg = '',$redirecturl = ''){
            return view('public/error',['msg'=>$msg,'url'=>$redirecturl]);
        }
    }

    public function ajax_set()
    {
        $type = request()->post('type');
        $name = request()->post('name');
        Session::set($type,$name);
    }
}